package utils;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
    private DBUtils() {
    }
    private static volatile MysqlDataSource mysqlDataSource;
    private static volatile Connection connection;

    private static MysqlDataSource getMysqlDataSource() {
        if (mysqlDataSource == null) {
            synchronized (DBUtils.class) {
                if (mysqlDataSource == null) {
                    mysqlDataSource = new MysqlDataSource();
                    mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/messagewall?character=utf8&useSSL=true");
                    mysqlDataSource.setUser("root");
                    mysqlDataSource.setPassword("123456");
                }
            }
        }
        return mysqlDataSource;
    }

    // 1.get connect
    public static Connection getConnection() {
        if (connection == null) { // 首次访问
            synchronized (DBUtils.class) {
                if (connection == null) {
                    try {
                        MysqlDataSource dataSource = getMysqlDataSource();
                        connection = (Connection) dataSource.getConnection();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        }
        return connection;
    }
    // 2.提供关闭资源的方法
    public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
//        if (connection != null) {
//            connection.close();
//        }
    }
}